import React, {PureComponent} from 'react';
import {
	StyleSheet,
	View,
	Text,
	Image,
	ListView,
	Dimensions,
	TouchableOpacity,
	Platform
} from 'react-native';
import PropTypes from 'prop-types'

// 获取屏幕宽度
let {width: WIDTH} = Dimensions.get('window');

// 全局变量
// 列数
let cols = 5;
// cell的宽高
let cellWH = Platform.OS === 'ios' ? 70 : 80;
// vMargin
let vMargin = (WIDTH - cellWH * cols) / (cols + 1);

/**
 * @FileName: TopListView
 * @Author: mazaiting
 * @Date: 2018/6/19
 * @Description:
 */
class TopListView extends PureComponent {
	// 属性
	static propTypes = {
		dataArr: PropTypes.string.isRequired
	};
	// 设置默认值
	static defaultProps = {
		dataArr: []
	};
	
	constructor(props) {
		super(props);
		// 创建数据源
		let ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
		this.state = {
			dataSource: ds.cloneWithRows(this.props.dataArr)
		}
	}
	
	render() {
		return (
			<ListView
				contentContainerStyle={styles.contentViewStyle}
				dataSource={this.state.dataSource}
				renderRow={(rowData) => this.renderRow(rowData)}
				scrollEnabled={false}
			/>
		)
	}
	
	/**
	 * 绘制条目
	 */
	renderRow(rowData) {
		return (
			<TouchableOpacity
				activeOpacity={0.5}
				onPress={() => alert(0)}
			>
				<View style={styles.cellStyle}>
					<Image
						source={{uri: rowData.image}}
						style={{
							width: 52,
							height: 52
						}}
					/>
					<Text style={styles.titleStyle}>{rowData.title}</Text>
				</View>
			</TouchableOpacity>
		)
	}
}

/**
 * 样式属性
 */
const styles = StyleSheet.create({
	container: {
		backgroundColor: '#DDD'
	},
	contentViewStyle: {
		flexDirection: 'row',
		// 多个Cell在同一行显示
		flexWrap: 'wrap',
		width: WIDTH
	},
	cellStyle: {
		// backgroundColor: 'red',
		width: cellWH,
		height: cellWH,
		justifyContent: 'center',
		alignItems: 'center',
		marginTop: 10,
		marginLeft: vMargin
	},
	titleStyle: {
		fontSize: Platform.OS === 'ios' ? 15 : 12,
		color: 'gray'
	}
});

/**
 * 导出当前Module
 */
module.exports = TopListView;